package com.lingjtx.common.security.config;

import com.alibaba.fastjson2.filter.ValueFilter;
import com.lingjtx.common.core.annotation.Sensitive;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class SensitiveSerializeFilter implements ValueFilter {
    @Override
    public Object apply(Object object, String name, Object value) {
        try {
            // 获取对象的字段
            Field field = object.getClass().getDeclaredField(name);
            // 检查字段是否标记了@Sensitive注解
            if (field.isAnnotationPresent(Sensitive.class)) {
                Sensitive sensitive = field.getDeclaredAnnotation(Sensitive.class);
                // 对字段值进行脱敏处理
                if (value instanceof String) {
                    return sensitive.type().getStrategy().apply(sensitive, (String) value);
                }
            }
        } catch (NoSuchFieldException e) {
            return value;
        }
        return value;
    }
}
